<?php
$csvfile = "ceglista.csv";
$outputfile = "companyllist.sql";
$startindex = 1;

/***********************************************/
function processRow($counter, $rowdata, $out) {
    $shortName = $rowdata[0];
    $address   = $rowdata[1];
    $phone     = $rowdata[2];
    $fax       = $rowdata[3];
    $email     = $rowdata[4];
    $hp        = $rowdata[5];
    $contact   = $rowdata[6];
    $post      = $rowdata[7];
    $product_freetype = $rowdata[8];
    $product_hscode = explode(", ", $rowdata[9]);
    $insert1 = "INSERT INTO companies (company_id, hphungarian, companyname, address, email1, fax1, phone1, contactperson1, jobtitle1) ".
              "VALUES ($counter, '$hp', '$shortName', '$address', '$email', '$fax', '$phone', '$contact', '$post');\r\n";
    fputs($out, $insert1);
    for ($i = 0; $i < count($product_hscode); $i++) {
        $insert2 = "INSERT INTO company_hs4_conn (company_id, hs4_id, imp_exp, freetype_text) ".
                  "VALUES ($counter, '" . $product_hscode[$i] . "', 1, '$product_freetype');\r\n";
        fputs($out, $insert2);
        $insert2 = "INSERT INTO company_hs4_conn (company_id, hs4_id, imp_exp, freetype_text) ".
                  "VALUES ($counter, '" . $product_hscode[$i] . "', 2, '$product_freetype');\r\n";
        fputs($out, $insert2);
    }
}
/***********************************************/

$f = fopen($csvfile, "r");
$c = 0;
$out = fopen($outputfile,  "w");
$counter = $startindex;
while (!feof($f)) {
    $c++;
    $row = rtrim(fgets($f));
    if ($c == 1) { continue; }
    $row = str_replace("\"", "", $row);
    $row = str_replace("'", "''", $row);
    $rowdata = explode(";", $row);
    processRow($counter, $rowdata, $out);
    $counter++;
}
fclose($f);
fclose($out);
?>
